var createError = require('http-errors');
var express = require('express');
var path = require('path');
var crl = require('./controller')
var cors = require('cors')
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const history = require('connect-history-api-fallback')




var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var facilityRouter = require('./routes/facility');
var filesRouter = require('./routes/files');
var noticeRouter = require('./routes/notice');
var socket = require('./routes/socket');


var app = express();
app.use(cors());
app.use(history()) //history中间件
    // view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json({ limit: '5mb' }));
// app.use(express.urlencoded({ extended: false }));  
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/facility', facilityRouter);
app.use('/files', filesRouter);
app.use('/notice', noticeRouter);
app.use('/socket', socket);

// app.use(express.static('./dist'))
// catch 404 and forward to error handler
app.use(function(req, res, next) {
    next(createError(404));
});
//websocket
// var ws = require("nodejs-websocket");
// console.log("开始建立连接...")
// var index = null, indexReady = false,num=0;
// var server = ws.createServer(function (conn) {
//   conn.on("text", function (str) {
//     console.log("收到的信息为:" + str)
//     if (str === "index") {
//       index = conn;
//     }
//     sendMess();
//     function sendMess(str) {
//       if (index && index.readyState === 1) {
//         index.sendText(num+'');
//         index.sendText(str?str:'');

//         num++
//         setTimeout(sendMess, 10000);
//       }
//     }
 
//   })
//   conn.on("close", function (code, reason) {
//     console.log("关闭连接")
//   });
//   conn.on("error", function (code, reason) {
//     console.log("异常关闭")
//   });
// }).listen(2078)

// error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;